import axios, { InternalAxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'
import { Response, ExtAxiosRequestOption } from '@/types/http'
import { message } from 'ant-design-vue'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { LOGIN_ROUTE } from '@/constants/base.contant'

// 自动处理错误
const handleError = (err: Response, options: ExtAxiosRequestOption) => {
  if (err.code === 20001) {
    const userStore = useUserStore()
    userStore.logout()
  }
  if (options.error === undefined) {
    message.error(err.msg)
  } else if (typeof options.error === 'function') {
    options.error(err)
  }
  return Promise.reject(err)
}

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  timeout: 60e3
})

// axios实例拦截请求
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig<any>) => {
    if (config.headers) {
      const userStore = useUserStore()
      config.headers['token'] = userStore.token
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// axios实例拦截响应
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.headers.token) {
      const userStore = useUserStore()
      userStore.setToken(response.headers.token)
    }
    const { code } = response.data
    // 异常处理
    if (code && code !== 200) {
      return handleError(response.data, response.config)
    }
    return response.data
  },
  (error: AxiosError) => {
    message.error('Network Error...')
    if (router.currentRoute.value.path !== LOGIN_ROUTE) {
      router.push('/error/500')
    }
    return Promise.reject(error)
  }
)

export default service
